<template>
  <div class="wrap" id="wrap" :style="{ backgroundImage: 'url(' + require('../assets/1120.jpg') + ')' }">
    <div style="
                    font-size: 80px;
                    float: left;
                    margin-top: 80px;
                    margin-left: 100px;
                    font-weight: 800;
                    letter-spacing: 5px;
                  ">
      投资项目经济评价原型系统v1.0
    </div>
    <el-card class="logGet">
      <el-form :model="forms" :rules="rules" ref="loginForm">
        <el-form-item label="登录名" prop="loginName" class="lgD" size="medium">
          <el-input v-model="forms.loginName" placeholder="请输入登录名" class="login-input"></el-input>
        </el-form-item>
        <el-form-item label="密&nbsp;&nbsp;&nbsp;&nbsp;码" prop="password" class="lgD" size="medium"
          style="margin-bottom: 15px">
          <el-input v-model="forms.password" placeholder="请输入密码" class="login-input" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox label="十四天内免密码登录" v-model="remember"></el-checkbox>
        </el-form-item>
        <el-form-item class="logC">
          <el-button type="primary" @click="submit">登录</el-button>
          <el-button @click="reset">重置</el-button>
          <el-button @click="CAStart">激活账户</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-dialog v-model="CAVisible" title="激活账号" :width="500" @close="CAVisible = false">
      <el-form>
        <el-form-item label="用户名：">
          <el-input v-model="CAForm.username" placeholder="请输入用户名" type="text" />
        </el-form-item>
        <el-form-item label="密码：">
          <el-input v-model="CAForm.password" placeholder="请输入密码" type="password" />
        </el-form-item>
        <el-form-item label="证书：">
          <el-input v-model="CAForm.license" placeholder="请输入证书" type="text" clearable />
        </el-form-item>
        <el-form-item label="过期时间：">
          <el-date-picker v-model="CAForm.expire_time" placeholder="过期时间" type="date" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="createAccount">
            激活
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { decrypt, encrypt } from "@/utils/crypto";
import { request } from "@/api/REQ"
import userApi, { startService } from "@/api/user/user";
import { defineComponent } from "vue";
import { useStore } from 'vuex' // 引入useStore 方法
import router from "@/router";
export default defineComponent({
  name: "LoginView",
  data () {
    return {
      store: useStore(),
      forms: {
        loginName: "",
        password: "",
      },
      rules: {
        loginName: [
          {
            required: true,
            message: "用户名不可为空",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不可为空",
            trigger: "blur",
          },
        ],
      },
      remember: false,
      CAVisible: false,
      CAForm: {
        username: '',
        password: '',
        license: '',
        expire_time: '',
        mac_address: ''
      }
    };
  },
  methods: {
    // CA激活账户
    async createAccount () {
      const de = JSON.parse(decrypt(this.CAForm.license))
      if (de.username !== this.CAForm.username
        || de.password !== this.CAForm.password) {
        ElMessage.error("证书错误")
        return
      }
      this.CAForm.expire_time = de.outDate
      this.CAForm.mac_address = de.macCode
      const fullres = await request.get("/user/validate", {
        params: this.CAForm
      })
      ElMessage.success("账户激活成功")
      this.CAVisible = false
    },
    // 打开CA弹窗
    CAStart () {
      this.CAVisible = true
      this.CAForm = {
        username: '',
        password: '',
        license: '',
        expire_time: '',
        mac_address: ''
      }
    },
    getCookie (cookieName) {

      var allcookies = document.cookie;

      // Get all the cookies pairs in an array
      let cookiearray = allcookies.split(';');
      // Now take key value pair out of this array
      for (var i = 0; i < cookiearray.length; i++) {
        let name = cookiearray[i].trim().split('=')[0];
        let value = cookiearray[i].trim().split('=')[1];
        if (name == cookieName) {
          return value;
        }
      }
      return ""
    },
    submit () {
      this.$refs["loginForm"].validate((flag) => {
        if (flag) {
          userApi.login(this.forms).then((res) => {
            if (res.data.code === 200) {
              const data = res.data.data;
              console.log(res)
              //this.store.dispatch("setToken",data.token)
              this.$store.dispatch("setToken", data.token);
              this.$store.dispatch("setMenu", data.menu);
              this.$store.dispatch("setUsername", data.username);
              this.$store.dispatch("setUserInfo", data.userInfo);
              this.$store.dispatch("setTime", new Date());
              this.$store.dispatch("setRoleList", data.roleInfo);
              document.cookie = "userId=" + data.userInfo.id;
              if (this.remember) {
                var now = new Date();
                //设置时间
                now.setDate(now.getDate() + 14)
                document.cookie = "userName=" + data.userInfo.username + ';expires=' + now.toUTCString();
                document.cookie = "pwd=" + data.userInfo.password + ';expires=' + now.toUTCString();
              }
              router.push("/help")
            } else {
              this.$message.error(res.data.message);
            }
          });
        }
      });
    },
    reset () {
      this.forms.loginName = "";
      this.forms.password = "";
    },
  },
  mounted () {
    if (this.getCookie("userName") !== "" && this.getCookie("userName") !== undefined) {
      this.forms.loginName = this.getCookie("userName")
      this.forms.password = this.getCookie("pwd")
      this.submit()
    }
  }

});

</script>

<style scoped>
#wrap {
  height: 100%;
  width: 100%;
  background-size: 100% 100%;
  background-position: center center;
  background-repeat: no-repeat;
  position: fixed;
}

#wrap .logGet {
  height: 300px;
  width: 400px;
  position: absolute;
  background-color: rgba(255, 255, 255, 0.5);
  top: 260px;
  right: 15%;
}

#wrap .logGet .lgD {
  width: 100%;
  height: 40px;
  position: relative;
  margin-bottom: 40px;
  margin-top: 40px;
  margin-right: auto;
  margin-left: auto;
}

#wrap .logGet .lgD>>>.el-form-item__label {
  font-size: 20px;
}

#wrap .logGet .logC>>>.el-form-item__content {
  margin-top: 0px;
  margin-right: auto;
  margin-bottom: 0px;
  margin-left: auto;
  display: block;
}

.logGet .lgD .login-input {
  width: 100%;
  height: 40px;
  text-indent: 2.5rem;
}
</style>
